<template>
  <div class="app-container">
    <div class="container" style="width: 100%;" v-if="!showAddStatus">
      <div class="filter-container">
        <el-form ref="queryForm" :model="listQuery" :rules="queryRules" label-position="left">
          <el-form-item size="mini" prop="goods_title" style="float: left;">
            <el-input v-model="listQuery.goods_title" placeholder="请输入物品名称" class="filter-item" style="width: 160px;margin-right:5px;"></el-input>
          </el-form-item>
          <el-form-item size="mini" prop="username" style="float: left;">
            <el-input v-model="listQuery.username" placeholder="请输入卖家名称" class="filter-item" style="width: 160px;margin-right:5px;"></el-input>
          </el-form-item>
          <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
          <el-button v-waves size="mini" class="filter-item" type="danger" @click="resetQueryForm('queryForm')">重置</el-button>
          <div style="float: right;margin-right: 60px">
            <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd(2)">发布 - 求购</el-button>
            <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd(1)">发布 - 出售</el-button>
          </div>
        </el-form>
      </div>
      <el-table v-loading="listLoading" :data="list" size="mini" highlight-current-row style="width: 100%">
        <el-table-column width="50px" align="left" label="ID">
          <template slot-scope="{row}">
            <span>{{ row.Id }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="物品名称">
          <template slot-scope="{row}">
            <span>{{ row.GoodsTitle }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="分类">
          <template slot-scope="{row}">
            <span>{{ row.CatName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left"  label="类型">
          <template slot-scope="{row}">
            <span v-if="row.TypeId === 1">出售</span>
            <span v-if="row.TypeId === 2">求购</span>
          </template>
        </el-table-column>
        <el-table-column align="left" width="150px" label="卖家">
          <template slot-scope="{row}">
            <span>{{ row.Username }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100px" align="left" label="售价">
          <template slot-scope="{row}">
            <span>{{ row.SalePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="交易地点">
          <template slot-scope="{row}">
            <span>{{ row.DistrictName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="购买时间">
          <template slot-scope="{row}">
            <span>{{ row.BoughtTimeStr }}</span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="状态">
          <template slot-scope="{row}">
            <i class="el-icon-check" style="color: green" v-if="row.Status"></i>
            <i class="el-icon-close" style="color: red" v-if="!row.Status"></i>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleStatus(row.Id)"
            >
              <span v-if="row.Status">禁用</span>
              <span v-if="!row.Status">启用</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="+total > 0" :total="total" :page.sync="listQuery.page_index" :limit.sync="listQuery.page_size" @pagination="getList" style="margin-top: 1px; padding-top: 10px;" />
    </div>
    <div v-if="showAddStatus" class="container" style="width: 100%;">
      <el-page-header :content="isEdit ? addData.type_id === 1 ? '编辑  出售 信息' : '编辑 求购 信息' : addData.type_id === 1 ? '新增 出售 信息' : '新增 求购 信息'" @back="goBack"></el-page-header>
      <el-form ref="addShGoodsForm" :rules="rules" :model="addData" label-position="left" label-width="90px" style="width: 100%; margin-top: 15px;">
        <el-container style="height: 760px; border: 1px solid #eee">
          <el-main style="margin-right:30px; width: 40%">
            <el-form-item label="发布类型" prop="goods_title">
              <span v-if="addData.type_id === 1" style="color: red; font-size: 20px;">出售 <span style="color: green; font-size: 16px;">二手物品</span></span>
              <span v-if="addData.type_id === 2" style="color: red; font-size: 20px;">求购 <span style="color: green; font-size: 16px;">二手物品</span></span>
            </el-form-item>
            <el-form-item label="物品名称" prop="goods_title">
              <el-input v-model="addData.goods_title" placeholder="不可有HTML标签" style="width: 580px;"/>
            </el-form-item>
            <el-form-item label="物品描述" prop="goods_desc">
              <el-input v-model="addData.goods_desc" :rows="10" type="textarea" style="width: 580px;"/>
            </el-form-item>
            <el-form-item label="列表图片" prop="image_list">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                list-type="picture-card"
                :headers="uploadHeader"
                :file-list="editInitImageList"
                :before-upload="beforeAvatarUpload"
                :on-success="handleUploadListImageSuccess"
                :on-preview="handleImagePreview"
                :on-remove="handleImageRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogImagePreviewVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-main>
          <el-aside style="background-color: #ffffff; width: 56%;">
            <el-form-item label="用户名称" prop="seller_id" size="mini" style="width: 325px;">
              <el-input v-model="addData.seller_id" placeholder="填写存在的用户名称" />
            </el-form-item>
            <el-form-item label="物品分类" size="mini" prop="cat_id">
              <el-select v-model="addData.cat_id" placeholder="请选择" style="width: 235px;">
                <el-option
                  v-for="item in catOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="交易地点" size="mini" prop="district_id">
              <el-cascader
                v-model="tmpSelectDistrictId"
                style="width: 355px;"
                :props="{ checkStrictly: true }"
                placeholder="请选择地点"
                :options="districtOptions"
                @change="handleDistrictChange">
              </el-cascader>
            </el-form-item>
            <el-form-item label="货币单位" size="mini" prop="sale_price" style="width: 325px;">
              <el-radio-group v-model="addData.currency_unit">
                <el-radio-button :label="i" :key="i" v-for="(name, i) in currencyOptions">{{ name }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="购买价格" size="mini" prop="bought_price" style="width: 325px;">
              <el-input v-model="addData.bought_price" placeholder="默认 0, 表示未提供原价"/>
            </el-form-item>
            <el-form-item label="出售价格" size="mini" prop="sale_price" style="width: 325px;">
              <el-input v-model="addData.sale_price" placeholder="默认0,表示价格面议"/>
            </el-form-item>
            <el-form-item label="购买时间" size="mini" prop="bought_time" style="width: 325px;">
              <el-date-picker
                style="width: 235px;"
                v-model="addData.bought_time"
                align="right"
                value-format="yyyy-MM-DD 00:00:00"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="封面图片" prop="image_cover">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                :show-file-list="false"
                :headers="uploadHeader"
                :on-preview="handleImagePreview"
                :on-success="handleUploadCoverImageSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageCoverUrl" :src="imageCoverUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <div>
              <el-button style="float: right; margin-right: 100px;" size="mini" type="primary" @click="handleAddSubmit()">提交</el-button>
            </div>
          </el-aside>
        </el-container>
      </el-form>
    </div>
  </div>
</template>

<script>
import { goodsList, goodsAdd, goodsStatus, goodsUploadImage } from '@/api/secondhand'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination/index'
import { getToken } from '@/utils/auth'
import { strLength, cleanObjectTreeData } from '@/utils/common'
import { checkCanAccess } from '@/utils/permission'

export default {
  name: 'SecondhandGoodsList',
  components: { Pagination },
  directives: { waves },
  data() {
    const checkGoodsName = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起，物品标题不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 72 || strLen < 6) {
        return callback(new Error('对不起， 物品标题为6-72个字符, 汉字为3个字符!'))
      } else {
        callback()
      }
    }
    return {
      // 副文本配置
      customConfig: {
        body_class: 'goods_id',
        height: 500,
        plugins: 'image',
        toolbar: 'image',
        images_upload_url: '',
        images_upload_handler: function(blobInfo, success, failure) {
          const imageData = new FormData()
          imageData.append('file', blobInfo.blob(), blobInfo.filename())
          goodsUploadImage(imageData).then(res => {
            if (res.success) {
              success(res.data.file_url)
            }
          })
        }
      },
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page_index: 1,
        page_size: 10,
        goods_title: '',
        username: ''
      },
      addData: {
        id: 0,
        type_id: 1,
        currency_unit: 1,
        seller_id: '',
        goods_title: '',
        goods_desc: '',
        cat_id: '',
        district_id: '',
        bought_price: '',
        sale_price: '',
        bought_time: '',
        image_cover: '',
        image_list: []
      },
      catOptions: [],
      districtOptions: [],
      typeOptions: [],
      currencyOptions: [],
      tmpSelectDistrictId: 0,
      showAddStatus: false,
      isEdit: false,
      rules: {
        seller_id: [
          { required: true, message: '需要填写租户名称', trigger: 'blur' }
        ],
        type_id: [
          { required: true, message: '需要填写类型', trigger: 'blur' }
        ],
        goods_title: [
          { required: true, message: '需要填写物品名称', trigger: 'blur' },
          { validator: checkGoodsName, trigger: 'blur' }
        ],
        goods_desc: [
          { required: true, message: '需要填写物品描述', trigger: 'blur' }
        ],
        cat_id: [
          { required: true, message: '需要选择分类ID', trigger: 'blur' }
        ],
        district_id: [
          { required: true, message: '需要选择城市ID', trigger: 'blur' }
        ],
        bought_price: [
          { required: true, message: '需要填写买进价', trigger: 'blur' }
        ],
        sale_price: [
          { required: true, message: '需要填写预售价格', trigger: 'blur' }
        ],
        image_list: [
          { required: true, message: '需要上传列表图片', trigger: 'blur' }
        ],
        image_cover: [
          { required: true, message: '需要上传封面图片', trigger: 'blur' }
        ],
        bought_time: [
          { required: true, message: '需要选择购买时间', trigger: 'blur' }
        ]
      },
      queryRules: {
        username: [
          { required: false, message: '需要填写卖家名称', trigger: 'blur' }
        ],
        goods_title: [
          { required: false, message: '需要填写物品标识', trigger: 'blur' }
        ]
      },
      dialogImageUrl: '',
      imageCoverUrl: '',
      tmpUploadImageList: [],
      editInitImageList: [],
      imageUploadUrl: process.env.VUE_APP_BASE_API + 'sh/goods/uploadImage',
      dialogImagePreviewVisible: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }, {
          text: '一月前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', date)
          }
        }, {
          text: '半年前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 30 * 6)
            picker.$emit('pick', date)
          }
        }, {
          text: '一年前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 30 * 12)
            picker.$emit('pick', date)
          }
        }
        ]
      }
    }
  },
  computed: {
    uploadHeader() {
      return { Authorization: 'bearer ' + getToken() }
    }
  },
  created() {
    this.resetQueryData()
    this.resetAddData()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      goodsList(this.listQuery).then(response => {
        if (response.success) {
          this.list = response.data.data.data
          this.total = response.data.data.total

          this.catOptions = response.data.cat_options
          this.districtOptions = cleanObjectTreeData(response.data.district_options)

          this.typeOptions = response.data.type_options
          this.currencyOptions = response.data.currency_options

          setTimeout(() => {
            this.listLoading = false
          }, 300)
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        }
      })
    },
    getDetail(item) {
      this.addData.id = item.Id
      this.addData.seller_id = item.SellerId
      this.addData.type_id = item.TypeId
      this.addData.goods_title = item.GoodsTitle
      this.addData.goods_desc = item.GoodsDesc
      this.addData.district_id = item.DistrictId
      this.tmpSelectDistrictId = item.DistrictId
      this.addData.cat_id = item.CatId
      this.addData.bought_price = item.BoughtPrice
      this.addData.bought_time = item.BoughtTimeStr
      this.addData.sale_price = item.SalePrice
      this.addData.image_cover = item.ImageCover
      this.imageCoverUrl = item.ImageCoverUrl
      this.addData.image_list = item.ImageList
      this.editInitImageList = item.ImageListArr
      console.log(item.ImageListArr)
    },
    handleAdd(typeId) {
      this.isEdit = false
      this.showAddStatus = true
      this.resetAddData()
      this.addData.type_id = typeId
    },
    handleEdit(item) {
      this.isEdit = true
      this.showAddStatus = true
      this.getDetail(item)
    },
    handleAddSubmit() {
      this.$refs['addShGoodsForm'].validate((valid) => {
        if (valid) {
          goodsAdd(this.addData).then((response) => {
            if (response.success === true) {
              this.$message({
                type: 'success',
                message: '添加二手商品信息成功'
              })
              this.goBack()
              this.getList()
              this.resetAddData()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    handleStatus(id) {
      console.log(id)
      this.$confirm('此操作将下架指定物品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsStatus(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: response.msg
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetAddData() {
      this.imageCoverUrl = ''
      this.tmpUploadImageList = []
      this.isEdit = false
      this.addData = {
        id: 0,
        type_id: 1,
        currency_unit: 1,
        seller_id: '',
        goods_title: '',
        goods_desc: '',
        cat_id: '',
        district_id: '',
        bought_price: '',
        sale_price: '',
        bought_time: '',
        image_cover: '',
        image_list: []
      }
    },
    resetQueryData() {
      this.listQuery = {
        page_index: 1,
        page_size: 10,
        goods_title: '',
        username: ''
      }
    },
    resetQueryForm(formName) {
      this.$refs[formName].resetFields()
    },
    beforeAvatarUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传封面图片只能是 JPG/PNG 格式!')
        return false
      }

      if (file.size / 1024 > 300) {
        this.$message.error('上传封面图片大小不能超过 300K!')
        return false
      }
      return true
    },
    checkCanAccess(path) {
      return checkCanAccess(path)
    },
    goBack() {
      this.showAddStatus = false
      this.resetAddData()
    },
    handleDistrictChange(item) {
      if (item.length > 0) {
        this.addData.district_id = item[item.length - 1]
      }
    },
    handleUploadCoverImageSuccess(res, file) {
      if (res.success) {
        this.addData.image_cover = res.data.file_name
        this.imageCoverUrl = URL.createObjectURL(file.raw)
      } else {
        this.$message({
          type: 'error',
          message: '上传图片失败'
        })
      }
    },
    handleUploadListImageSuccess(res, file, fileList) {
      if (res.success) {
        const imageNameList = []
        console.log(fileList)
        for (let i = 0; i < fileList.length; i++) {
          if ('image_name' in fileList[i]) {
            imageNameList.push(fileList[i].image_name)
          } else {
            imageNameList.push(fileList[i].response.data.file_name)
          }

        }
        this.addData.image_list = imageNameList.join(',')
      } else {
        this.$message({
          type: 'error',
          message: '上传图片失败'
        })
      }
    },
    handleImageRemove(file, fileList) {
      const imageNameList = []
      for (let i = 0; i < fileList.length; i++) {
        imageNameList.push(fileList[i].response.data.file_name)
      }
      this.addData.image_list = imageNameList.join(',')
    },
    handleImagePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImagePreviewVisible = true
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 108px;
    height: 108px;
    line-height: 108px;
    text-align: center;
  }
  .avatar {
    width: 108px;
    height: 108px;
    display: block;
  }
  .el-upload-list--picture-card .el-upload-list__item {
    width: 108px;
    height: 108px;
  }
  .el-upload--picture-card {
    width: 108px;
    height: 108px;
    line-height: 108px;
  }
</style>
